<template>
  <div class="user-management-panel">
    <div class="panel-header">
      <h3>用户管理</h3>
      <div class="header-actions">
        <button @click="showCreateModal" class="create-btn" v-if="canCreateUser">
          新增用户
        </button>
        <button @click="toggleRegistration" class="toggle-btn">
          {{ registrationEnabled ? "禁用注册" : "启用注册" }}
        </button>
        <button @click="refreshUsers" class="refresh-btn">刷新</button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters-section">
      <div class="search-bar">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索用户名..." 
          class="search-input"
        />
        <select v-model="roleFilter" class="filter-select">
          <option value="">全部角色</option>
          <option value="admin">管理员</option>
          <option value="user">普通用户</option>
        </select>
        <button @click="clearFilters" class="clear-btn">清除筛选</button>
      </div>
      
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <span class="selected-count">已选择 {{ selectedUsers.length }} 个用户</span>
        <button @click="batchDelete" class="batch-delete-btn" v-if="canDeleteUser">
          批量删除
        </button>
        <select @change="batchChangeRole" class="batch-role-select" v-if="canUpdateUser">
          <option value="">批量设置角色</option>
          <option value="user">设为普通用户</option>
          <option value="admin">设为管理员</option>
        </select>
      </div>
    </div>

    <div class="users-list">
      <div class="list-header">
        <div class="header-item checkbox-header">
          <input 
            type="checkbox" 
            :checked="isAllSelected" 
            @change="toggleSelectAll"
            :indeterminate="isIndeterminate"
          />
        </div>
        <div class="header-item">用户名</div>
        <div class="header-item">角色</div>
        <div class="header-item">权限数</div>
        <div class="header-item">注册时间</div>
        <div class="header-item">状态</div>
        <div class="header-item">操作</div>
      </div>

      <div v-if="filteredUsers.length === 0" class="no-users">
        <div class="empty-state">
          <div class="empty-icon">👥</div>
          <h4>暂无用户</h4>
          <p>{{ searchQuery || roleFilter ? '没有找到符合条件的用户' : '还没有用户，请先创建用户' }}</p>
        </div>
      </div>

      <div v-for="user in paginatedUsers" :key="user.id" class="user-item">
        <div class="user-info">
          <div class="checkbox-cell">
            <input 
              type="checkbox" 
              :value="user.id" 
              v-model="selectedUsers"
              :disabled="!canSelectUser(user)"
            />
          </div>
          <div class="username" @click="viewUser(user)">
            <span class="user-name">{{ user.username }}</span>
            <span v-if="isCurrentUser(user.id)" class="current-user-badge">当前用户</span>
          </div>
          <div class="role">
            <span :class="['role-badge', user.role]">{{ getRoleText(user.role) }}</span>
          </div>
          <div class="permissions-count">
            {{ (user.permissions || []).length }}
          </div>
          <div class="created-at">{{ formatDate(user.createdAt) }}</div>
          <div class="status">
            <span class="status-active">活跃</span>
          </div>
          <div class="actions">
            <button @click="viewUser(user)" class="view-btn" title="查看详情">
              👁️
            </button>
            <button 
              @click="editUser(user)" 
              class="edit-btn" 
              v-if="canEditUser(user)"
              title="编辑用户"
            >
              ✏️
            </button>

            <button
              v-if="canChangeRole(user)"
              @click="changeUserRole(user.id, user.role === 'user' ? 'admin' : 'user')"
              class="role-btn"
              :title="user.role === 'user' ? '设为管理员' : '取消管理员'"
            >
              {{ user.role === "user" ? "🔼" : "🔽" }}
            </button>
            <button
              v-if="canDeleteSingleUser(user)"
              @click="deleteUser(user.id)"
              class="delete-btn"
              title="删除用户"
            >
              🗑️
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalPages > 1">
      <button 
        @click="currentPage = 1" 
        :disabled="currentPage === 1"
        class="page-btn"
      >
        首页
      </button>
      <button 
        @click="currentPage--" 
        :disabled="currentPage === 1"
        class="page-btn"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页
      </span>
      <button 
        @click="currentPage++" 
        :disabled="currentPage === totalPages"
        class="page-btn"
      >
        下一页
      </button>
      <button 
        @click="currentPage = totalPages" 
        :disabled="currentPage === totalPages"
        class="page-btn"
      >
        末页
      </button>
    </div>

    <!-- 用户详情模态框 -->
    <UserDetailModal 
      ref="userDetailModal"
      :show="showModal"
      :user="selectedUser"
      :isNewUser="isCreatingUser"
      @close="closeModal"
      @user-saved="handleUserSaved"
    />

    <div class="stats-section">
      <h4>用户统计</h4>
      <div class="stats-grid">
        <div class="stat-item">
          <span class="stat-label">总用户数</span>
          <span class="stat-value">{{ users.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">管理员</span>
          <span class="stat-value">{{ adminCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">普通用户</span>
          <span class="stat-value">{{ userCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">注册状态</span>
          <span
            class="stat-value"
            :class="registrationEnabled ? 'enabled' : 'disabled'"
          >
            {{ registrationEnabled ? "已启用" : "已禁用" }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import authAPI from "@/utils/authAPI";
import UserDetailModal from "./UserDetailModal.vue";

export default {
  name: "UserManagementPanel",
  components: {
    UserDetailModal
  },
  data() {
    return {
      users: [],
      registrationEnabled: true,
      isLoading: false,
      searchQuery: '',
      roleFilter: '',
      selectedUsers: [],
      showModal: false,
      selectedUser: {},
      isCreatingUser: false,
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {
    // 权限检查
    canCreateUser() {
      const currentUser = authAPI.getCurrentUser();
      return currentUser && (currentUser.role === 'admin' || authAPI.hasPermission('user:create'));
    },
    canUpdateUser() {
      const currentUser = authAPI.getCurrentUser();
      return currentUser && (currentUser.role === 'admin' || authAPI.hasPermission('user:update'));
    },
    canDeleteUser() {
      const currentUser = authAPI.getCurrentUser();
      return currentUser && (currentUser.role === 'admin' || authAPI.hasPermission('user:delete'));
    },

    // 用户筛选
    filteredUsers() {
      let filtered = this.users;

      // 搜索筛选
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        filtered = filtered.filter(user => 
          user.username.toLowerCase().includes(query)
        );
      }

      // 角色筛选
      if (this.roleFilter) {
        filtered = filtered.filter(user => user.role === this.roleFilter);
      }

      return filtered;
    },

    // 分页
    totalPages() {
      return Math.ceil(this.filteredUsers.length / this.pageSize);
    },
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredUsers.slice(start, end);
    },

    // 全选相关
    isAllSelected() {
      return this.selectedUsers.length > 0 && 
             this.selectedUsers.length === this.selectableUsers.length;
    },
    isIndeterminate() {
      return this.selectedUsers.length > 0 && 
             this.selectedUsers.length < this.selectableUsers.length;
    },
    selectableUsers() {
      return this.paginatedUsers.filter(user => this.canSelectUser(user));
    },

    // 统计
    adminCount() {
      return this.filteredUsers.filter((user) => user.role === "admin").length;
    },
    userCount() {
      return this.filteredUsers.filter((user) => user.role === "user").length;
    },
  },
  async mounted() {
    await this.loadUsers();
    await this.loadRegistrationStatus();
  },
  watch: {
    searchQuery() {
      this.currentPage = 1;
    },
    roleFilter() {
      this.currentPage = 1;
    }
  },
  methods: {
    async loadUsers() {
      try {
        this.isLoading = true;
        const result = await authAPI.getAllUsers();

        if (result.success) {
          this.users = result.data;
        } else {
          console.error("加载用户失败:", result.error);
        }
      } catch (error) {
        console.error("加载用户错误:", error);
      } finally {
        this.isLoading = false;
      }
    },

    async loadRegistrationStatus() {
      try {
        this.registrationEnabled = await authAPI.getRegistrationStatus();
      } catch (error) {
        console.error("获取注册状态失败:", error);
      }
    },

    // 筛选和搜索
    clearFilters() {
      this.searchQuery = '';
      this.roleFilter = '';
      this.currentPage = 1;
    },

    // 用户选择
    canSelectUser(user) {
      const currentUser = authAPI.getCurrentUser();
      if (!currentUser) return false;
      // 不能选择自己
      if (currentUser.id === user.id) return false;
      // 普通用户不能选择管理员
      if (currentUser.role !== 'admin' && user.role === 'admin') return false;
      return this.canUpdateUser || this.canDeleteUser;
    },

    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedUsers = [];
      } else {
        this.selectedUsers = this.selectableUsers.map(user => user.id);
      }
    },

    isCurrentUser(userId) {
      const currentUser = authAPI.getCurrentUser();
      return currentUser && currentUser.id === userId;
    },

    // 权限检查方法
    canEditUser(user) {
      const currentUser = authAPI.getCurrentUser();
      if (!currentUser) return false;
      if (currentUser.role === 'admin') return true;
      if (currentUser.id === user.id) return false; // 不能编辑自己
      return authAPI.hasPermission('user:update');
    },



    canChangeRole(user) {
      const currentUser = authAPI.getCurrentUser();
      if (!currentUser) return false;
      if (currentUser.id === user.id) return false; // 不能修改自己的角色
      if (currentUser.role === 'admin') return true;
      // 普通用户不能修改管理员角色
      if (user.role === 'admin') return false;
      return authAPI.hasPermission('user:update');
    },

    canDeleteSingleUser(user) {
      const currentUser = authAPI.getCurrentUser();
      if (!currentUser) return false;
      if (currentUser.id === user.id) return false; // 不能删除自己
      if (currentUser.role === 'admin') return true;
      // 普通用户不能删除管理员
      if (user.role === 'admin') return false;
      return authAPI.hasPermission('user:delete');
    },

    // 模态框操作
    showCreateModal() {
      this.selectedUser = {};
      this.isCreatingUser = true;
      this.showModal = true;
    },

    viewUser(user) {
      this.selectedUser = { ...user };
      this.isCreatingUser = false;
      this.showModal = true;
    },

    editUser(user) {
      this.selectedUser = { ...user };
      this.isCreatingUser = false;
      this.showModal = true;
      
      // 通过nextTick确保模态框已经打开，然后自动进入编辑模式
      this.$nextTick(() => {
        // 触发编辑模式（通过refs调用子组件方法）
        if (this.$refs && this.$refs.userDetailModal) {
          this.$refs.userDetailModal.startEditing();
        }
      });
    },



    closeModal() {
      this.showModal = false;
      this.selectedUser = {};
      this.isCreatingUser = false;
    },

    // eslint-disable-next-line no-unused-vars
    async handleUserSaved(user) {
      await this.loadUsers();
      this.selectedUsers = []; // 清除选择
      // 如果是当前页面没有用户了，回到上一页
      if (this.paginatedUsers.length === 0 && this.currentPage > 1) {
        this.currentPage--;
      }
    },

    // 批量操作
    async batchDelete() {
      if (this.selectedUsers.length === 0) return;

      const usernames = this.selectedUsers.map(id => {
        const user = this.users.find(u => u.id === id);
        return user ? user.username : id;
      }).join(', ');

      if (!confirm(`确定要删除以下 ${this.selectedUsers.length} 个用户吗？\n${usernames}\n\n此操作不可撤销。`)) {
        return;
      }

      try {
        const result = await authAPI.batchDeleteUsers(this.selectedUsers);
        if (result.success) {
          await this.loadUsers();
          this.selectedUsers = [];
          alert(`成功删除 ${result.deletedCount || this.selectedUsers.length} 个用户`);
        } else {
          alert("批量删除失败: " + result.error);
        }
      } catch (error) {
        console.error("批量删除用户失败:", error);
        alert("批量删除失败，请重试");
      }
    },

    async batchChangeRole(event) {
      const newRole = event.target.value;
      if (!newRole || this.selectedUsers.length === 0) {
        event.target.value = ''; // 重置选择
        return;
      }

      const usernames = this.selectedUsers.map(id => {
        const user = this.users.find(u => u.id === id);
        return user ? user.username : id;
      }).join(', ');

      const roleText = newRole === 'admin' ? '管理员' : '普通用户';
      if (!confirm(`确定要将以下 ${this.selectedUsers.length} 个用户的角色设置为"${roleText}"吗？\n${usernames}`)) {
        event.target.value = ''; // 重置选择
        return;
      }

      try {
        const result = await authAPI.batchUpdateUserRoles(this.selectedUsers, newRole);
        if (result.success) {
          await this.loadUsers();
          this.selectedUsers = [];
          alert(`成功更新 ${result.updatedCount || this.selectedUsers.length} 个用户的角色`);
        } else {
          alert("批量更新角色失败: " + result.error);
        }
      } catch (error) {
        console.error("批量更新用户角色失败:", error);
        alert("批量更新角色失败，请重试");
      } finally {
        event.target.value = ''; // 重置选择
      }
    },

    // 原有方法
    async toggleRegistration() {
      try {
        const result = await authAPI.toggleRegistration();
        if (result.success) {
          this.registrationEnabled = result.enabled;
          alert(`注册功能已${this.registrationEnabled ? "启用" : "禁用"}`);
        } else {
          alert("操作失败: " + result.error);
        }
      } catch (error) {
        console.error("切换注册状态失败:", error);
        alert("操作失败，请重试");
      }
    },

    async changeUserRole(userId, newRole) {
      try {
        const result = await authAPI.changeUserRole(userId, newRole);
        if (result.success) {
          await this.loadUsers();
          alert("用户角色更新成功");
        } else {
          alert("更新失败: " + result.error);
        }
      } catch (error) {
        console.error("更新用户角色失败:", error);
        alert("更新失败，请重试");
      }
    },

    async deleteUser(userId) {
      if (!confirm("确定要删除这个用户吗？此操作不可撤销。")) {
        return;
      }

      try {
        const result = await authAPI.deleteUser(userId);
        if (result.success) {
          await this.loadUsers();
          this.selectedUsers = this.selectedUsers.filter(id => id !== userId); // 清除选择
          alert("用户删除成功");
        } else {
          alert("删除失败: " + result.error);
        }
      } catch (error) {
        console.error("删除用户失败:", error);
        alert("删除失败，请重试");
      }
    },

    async refreshUsers() {
      await this.loadUsers();
      this.selectedUsers = []; // 清除选择
    },

    formatDate(dateString) {
      if (!dateString) return "未知";
      return new Date(dateString).toLocaleDateString("zh-CN");
    },

    getRoleText(role) {
      const roleMap = {
        admin: "管理员",
        user: "普通用户",
      };
      return roleMap[role] || "未知";
    },
  },
};
</script>

<style scoped lang="scss">
.user-management-panel {
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    color: #fff;
    font-size: 18px;
  }

  .header-actions {
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      transition: all 0.3s ease;

      &.create-btn {
        background: #27ae60;
        color: #fff;

        &:hover {
          background: #229954;
          transform: translateY(-1px);
        }
      }

      &.toggle-btn {
        background: #f39c12;
        color: #fff;

        &:hover {
          background: #e67e22;
        }
      }

      &.refresh-btn {
        background: #4a90e2;
        color: #fff;

        &:hover {
          background: #357abd;
        }
      }
    }
  }
}

// 搜索和筛选区域
.filters-section {
  background: #2a2a2a;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;

  .search-bar {
    display: flex;
    gap: 15px;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 15px;

    .search-input, .filter-select {
      padding: 8px 12px;
      border: 1px solid #444;
      border-radius: 4px;
      background: #333;
      color: #fff;
      font-size: 14px;

      &:focus {
        outline: none;
        border-color: #4a90e2;
      }
    }

    .search-input {
      flex: 1;
      min-width: 200px;
    }

    .filter-select {
      min-width: 120px;
    }

    .clear-btn {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      background: #666;
      color: #fff;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        background: #555;
      }
    }
  }

  .batch-actions {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 10px 0;
    border-top: 1px solid #444;

    .selected-count {
      color: #4a90e2;
      font-weight: bold;
      font-size: 14px;
    }

    .batch-delete-btn {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      background: #e74c3c;
      color: #fff;
      cursor: pointer;
      font-size: 13px;

      &:hover {
        background: #c0392b;
      }
    }

    .batch-role-select {
      padding: 6px 10px;
      border: 1px solid #444;
      border-radius: 4px;
      background: #333;
      color: #fff;
      font-size: 13px;
      cursor: pointer;

      &:focus {
        outline: none;
        border-color: #4a90e2;
      }
    }
  }
}

.users-list {
  background: #2a2a2a;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;

  .list-header {
    display: grid;
    grid-template-columns: 50px 2fr 1fr 80px 1fr 80px 150px;
    gap: 15px;
    padding: 15px 20px;
    background: #333;
    font-weight: bold;
    color: #fff;
    font-size: 14px;
    align-items: center;

    .checkbox-header {
      display: flex;
      justify-content: center;
      align-items: center;

      input[type="checkbox"] {
        width: 16px;
        height: 16px;
        accent-color: #4a90e2;
      }
    }
  }

  .no-users {
    padding: 40px 20px;
    text-align: center;

    .empty-state {
      .empty-icon {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.6;
      }

      h4 {
        color: #fff;
        margin: 0 0 0.5rem 0;
        font-size: 1.2rem;
      }

      p {
        color: #ccc;
        margin: 0;
        font-size: 0.9rem;
      }
    }
  }

  .user-item {
    border-bottom: 1px solid #444;
    transition: background-color 0.2s ease;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background: rgba(255, 255, 255, 0.02);
    }

    .user-info {
      display: grid;
      grid-template-columns: 50px 2fr 1fr 80px 1fr 80px 150px;
      gap: 15px;
      padding: 15px 20px;
      align-items: center;

      .checkbox-cell {
        display: flex;
        justify-content: center;
        align-items: center;

        input[type="checkbox"] {
          width: 16px;
          height: 16px;
          accent-color: #4a90e2;

          &:disabled {
            opacity: 0.5;
          }
        }
      }

      .username {
        display: flex;
        flex-direction: column;
        cursor: pointer;
        gap: 4px;

        .user-name {
          color: #fff;
          font-weight: bold;
          font-size: 14px;

          &:hover {
            color: #4a90e2;
          }
        }

        .current-user-badge {
          background: #3498db;
          color: #fff;
          padding: 2px 6px;
          border-radius: 8px;
          font-size: 10px;
          width: fit-content;
        }
      }

      .role {
        .role-badge {
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: bold;
          width: fit-content;

          &.admin {
            background: #e74c3c;
            color: #fff;
          }

          &.user {
            background: #4a90e2;
            color: #fff;
          }
        }
      }

      .permissions-count {
        color: #ccc;
        font-size: 13px;
        text-align: center;
      }

      .created-at {
        color: #ccc;
        font-size: 12px;
      }

      .status {
        display: flex;
        justify-content: center;

        .status-active {
          background: #27ae60;
          color: #fff;
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          width: fit-content;
        }
      }

      .actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;

        button {
          padding: 6px 8px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
          transition: all 0.2s ease;
          min-width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover {
            transform: translateY(-1px);
          }

          &.view-btn {
            background: #4a90e2;
            color: #fff;

            &:hover {
              background: #357abd;
            }
          }

          &.edit-btn {
            background: #f39c12;
            color: #fff;

            &:hover {
              background: #e67e22;
            }
          }



          &.role-btn {
            background: #9b59b6;
            color: #fff;

            &:hover {
              background: #8e44ad;
            }
          }

          &.delete-btn {
            background: #e74c3c;
            color: #fff;

            &:hover {
              background: #c0392b;
            }
          }
        }
      }
    }
  }
}

// 分页
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin: 20px 0;

  .page-btn {
    padding: 8px 16px;
    border: 1px solid #444;
    border-radius: 4px;
    background: #333;
    color: #fff;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;

    &:hover:not(:disabled) {
      background: #4a90e2;
      border-color: #4a90e2;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }

  .page-info {
    color: #ccc;
    font-size: 14px;
    margin: 0 10px;
  }
}

.stats-section {
  background: #2a2a2a;
  border-radius: 8px;
  padding: 20px;

  h4 {
    margin: 0 0 15px 0;
    color: #fff;
    font-size: 16px;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 15px;
      background: #333;
      border-radius: 6px;

      .stat-label {
        color: #ccc;
        font-size: 12px;
        margin-bottom: 5px;
      }

      .stat-value {
        color: #fff;
        font-size: 18px;
        font-weight: bold;

        &.enabled {
          color: #27ae60;
        }

        &.disabled {
          color: #e74c3c;
        }
      }
    }
  }
}
</style>
